<template>
  <div class="login-form">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <p>"易儿宝"母婴闲置用品交易平台</p>
      <p>欢迎登录</p>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item prop="usertype">
        <el-radio-group v-model="form.usertype">
          <el-radio label="用户" value="0"></el-radio>
          <el-radio label="管理员"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  class="login-btn" @click="loginFn">登录</el-button>
        <el-link type="info" @click="gotoRegesterFn">去注册</el-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { mapMutations } from 'vuex'
export default {
  name: 'my-login',
  data () {
    return {
      form: {
        username: '',
        password: '',
        usertype: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-z0-9]{1,10}$/, message: '用户名必须是1-10位的数字英文组合', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须为6-15位的非空字符串', trigger: 'blur' }
        ],
        usertype: [
          { required: true, message: '请选择登录角色', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    ...mapMutations(['getToken']),
    gotoRegesterFn () {
      this.$router.push('/register')
    },
    // 登录
    loginFn () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const { data } = await loginAPI(this.form)
          if (data.status !== 0) return this.$message.error(data.message)
          this.getToken(data.token)
          if (this.form.usertype === '用户') {
            this.$router.push('/layout')
          } else {
            this.$router.push('/adminlayout')
          }
          this.$message.success('登陆成功')
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.login-form{
  background: url('../../assets/images/login.png') center;
  background-size: cover;
  height: 100%;
}
.el-form{
  position: absolute;
  width: 400px;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  border: 1px #ffa6ff solid;
  border-radius: 20px;
  padding:10px 30px;
  opacity: 0.7;
  background-color: aliceblue;
}
.el-form p{
  color:#9F0050;
  font-size: 19px;
  text-align: center;
}
.login-btn{
  width: 100%;
}
.el-link{
  float: left;
}
</style>
